﻿using System;
using System.Collections.Generic;
using System.Linq;
using Icms.Core;
using Icms.Core.Model;
using Icms.Core.Repository;
using Icms.Core.Service;

namespace Icms.Service
{
    public class BackupLogService : IBackupLogService
    {
        private readonly IRepo2<BackupLog> logsRepo;
        private readonly IRepo<Court> courtRepo;

        public BackupLogService(IRepo2<BackupLog> logsRepo, IRepo<Court> courtRepo)
        {
            this.logsRepo = logsRepo;
            this.courtRepo = courtRepo;
        }

        public IEnumerable<BackupLog> GetPage(int page, int pageSize, Guid? courtId, out int count)
        {
            var logs = logsRepo.GetAll();
            if (courtId.HasValue) logs = logs.Where(o => o.CourtId == courtId);
            count = logs.Count();
            logs = logs.Pag(page, pageSize).ToList();

            var courts = courtRepo.Where(o => logs.Select(l => l.CourtId).Contains(o.Id));
            logs = logs.Select(o =>
                                new BackupLog
                                    {
                                        CourtId = o.CourtId,
                                        Date = o.Date,
                                        Court = courts.SingleOrDefault(c => c.Id == o.CourtId)
                                    });

            return logs;
        }
    }
}